package com.github.defense.plugin.gray.holder;

import com.github.defense.plugin.gray.constants.MetaDataConstant;
import com.google.common.collect.Maps;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: lettger
 * @Date: 2021/6/22 10:43 上午
 */
@Data
public class MetaDataHolder {

    private static final String POINT = ".";

    private static final Pattern pattern = Pattern.compile("\\d+");

    public static Map<String, HashMap> getGrayMetaData(Map<String, Object> metaData) {
        if (Objects.isNull(metaData)) {
            return Maps.newHashMap();
        }
        Map<String, HashMap> map = new HashMap<>();
        for (Map.Entry<String, Object> entry : metaData.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key.contains(MetaDataConstant.GRAY_DEFINITION_PREFIX)) {
                String number = getFirstNumber(key);
                if (!StringUtils.isEmpty(number)) {
                    HashMap hashMap = map.get(number);
                    if (null == hashMap) {
                        hashMap = new HashMap();
                    }
                    hashMap.put(getKeyName(key), value);
                    map.put(number, hashMap);
                }
            }
        }
        return map;
    }


    /**
     * 获取第一个数字
     *
     * @param content
     * @return
     */
    private static String getFirstNumber(String content) {
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    /**
     * 获取key名称
     *
     * @param content
     * @return
     */
    private static String getKeyName(String content) {
        return content.substring(content.lastIndexOf(POINT) + 1);
    }
}
